package com.wanpinghui.supplier.message;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.wanpinghui.supplier.Config;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.AddAddrBookFriendsActivity;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.message.adapter.P2PMsgAdapter;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.message.nim.NimUserExt;
import com.wanpinghui.supplier.message.nim.WPHMsg;
import com.wanpinghui.supplier.oauth.LoginActivity;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.product.ProductListActivity;
import com.wanpinghui.supplier.user.order.OrderDetailActivity;
import com.wanpinghui.supplier.utils.FileUtil;
import com.wanpinghui.supplier.widgets.IMInputView;
import com.wanpinghui.supplier.widgets.MessageP2PLayout;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.message.MessageService;
import com.wanpinghui.wphlibrary.model.message.bean.MessageType;
import com.wanpinghui.wphlibrary.model.message.bean.MessagesExt;
import com.wanpinghui.wphlibrary.model.message.bean.MsgBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.BaseUserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.order.bean.OrderItemBean;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorFragment;
import me.nereo.multi_image_selector.PhotoPickManager;
import retrofit.callback.YRequestCallback;

/**
 * Created by xiongning on 17-12-1.
 */
@ContentView(R.layout.layout_p2p_message)
public class MessageP2PActivity extends BaseActivity implements NimManager.INIMListener, NimManager.INIMRcvMsgListener, YRequestCallback, IMInputView.IMinputListener {

    @ViewInject(R.id.ll_title)
    private LinearLayout ll_title;

//    @ViewInject(R.id.view_backtrack)
//    private LinearLayout view_backtrack;

//    @ViewInject(R.id.sv)
//    private SpinView sv;

//    @ViewInject(R.id.tv_title_panel)
//    private TextView tv_title_panel;

    @ViewInject(R.id.rl_tip_area)
    private RelativeLayout rl_tip_area;

    @ViewInject(R.id.ll_rootview)
    private LinearLayout ll_rootview;

    @ViewInject(R.id.tv_msg_tip)
    private TextView tv_msg_tip;

    @ViewInject(R.id.btn_login)
    private ThrottleButton btn_login;

    @ViewInject(R.id.tv_info)
    private TextView tv_info;

    @ViewInject(R.id.recv_msg_list)
    private RecyclerView recv_msg_list;

    @ViewInject(R.id.imv)
    private IMInputView imv;

    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser tpl_title;

    @ViewInject(R.id.progressBar)
    private ProgressBar progressBar;

    @ViewInject(R.id.ll_messages)
    private MessageP2PLayout mLayoutMessages;

//    @ViewInject(R.id.rl_softinput_bottom)
//    private RelativeLayout rl_softinput_bottom;

    private P2PMsgAdapter mAdapter = null;

    List<MsgBean> datas = new ArrayList<>();

    private boolean isEtMsgTouch = false;

    /*除去title栏的布局高度*/
    private int mMaxHeight;

    /*软键盘高度*/
    private int mSoftInputHeight;

    private String showTitle = null;

    private BaseUserBean mChatUser = null;

    private String cateStr=null;

    private String demand = "";

    private String city = null;

    private String chatIM = "";

    private String group_id = null;

    private SwipeRefreshLayout.OnRefreshListener refreshListener;

    private static final int REQUEST_SELECT_PHOTO = 1;

    private static final int REQUEST_TAKE_PHOTO = 2;

    private static final int REQUEST_SELECT_DOC = 3;

    private static final int REQUEST_RECORD_AUDIO = 4;

    private File mTmpFile;

    private LinearLayoutManager mLinearLayoutManager;

    private boolean move;

    private int mIndex = 0;
    private boolean loading;
    private long lastCrateAt;
    private String orderJsonStr;//订单内容
    private UserBean userBean;
    private NimUserInfo toUserInfo;

    @Override
    public String getName() {
        return this.getLocalClassName();
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        if (!LoginUtil.loginFilter(this)) {
            finish();
        }
        userBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
        FileUtil.setActivity(this);
        mAdapter = new P2PMsgAdapter(this);
//        ll_rootview.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > DensityUtil.getScreenHeight()/3)){
//                 //   imv.hideAttachArea();
//                 //   Toast.makeText(MessageP2PActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();
//
//                }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > DensityUtil.getScreenHeight()/3)){
//                    imv.getEt_msg().setFocusableInTouchMode(false);
//                    imv.getEt_msg().setFocusable(false);
//                //    Toast.makeText(MessageP2PActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();
//
//                }
//            }
//        });

        imv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                imv.getGlobalVisibleRect(r);
                if (isEtMsgTouch) {
                    //   imv.hideAttachArea();
                    isEtMsgTouch = false;
                    imv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    mSoftInputHeight = getResources().getDisplayMetrics().heightPixels - r.bottom;//软键盘高度
                    Log.d("mydebug---", "软键盘高度 ： " + mSoftInputHeight);
                    //rl_softinput_bottom.getLayoutParams().height = mSoftInputHeight;
                    //rl_softinput_bottom.requestLayout();
                } else {
                    Rect rect = new Rect();
                    ll_title.getGlobalVisibleRect(rect);
                    mMaxHeight = r.bottom - rect.bottom;
                    Log.d("mydebug---", "mMaxHeight ： " + mMaxHeight);
                }
            }
        });

        imv.getEt_msg().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                if(!isSoftInputNotShow()){
//                    setSoftInputShow();
//                }
                isEtMsgTouch = true;
                imv.getEt_msg().setFocusableInTouchMode(true);
                imv.getEt_msg().setFocusable(true);
                //rl_softinput_bottom.setVisibility(View.GONE);
                return false;
            }
        });

    }

    @Override
    public void bindEvents() {

//        view_backtrack.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        tpl_title.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tpl_title.setOnClickAddition(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getMsg_Type() != WPHMsg.TYPE_SERVICE) {
                    Intent intent = new Intent(MessageP2PActivity.this, MessageDetailActivity.class);
                    intent.putExtra("user_id", Integer.parseInt(chatIM));
                    intent.putExtra("mine_id", Integer.parseInt(userBean.getUser().getId()));
                    startActivity(intent);
                } else {
                    showWarningText("和客服聊天不支持此操作");
                }

            }
        });

        imv.registerIMinputListener(this);

        btn_login.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MessageP2PActivity.this, LoginActivity.class));
            }
        });

        recv_msg_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int last = mLinearLayoutManager.findLastVisibleItemPosition();
                int first = mLinearLayoutManager.findFirstVisibleItemPosition();
                int count = mLinearLayoutManager.getChildCount();

                System.out.println("first=" + first + ";last=" + last + ";count=" + count);
                if (last == mAdapter.getItemCount() - 1 && !loading) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        mAdapter.setMsgClickListener(new P2PMsgAdapter.OnMsgClickListener() {
            @Override
            public void onOrderClick(OrderItemBean bean) {
                if (bean != null) {
                    Intent intent = new Intent(MessageP2PActivity.this, OrderDetailActivity.class);
                    intent.putExtra("order", new Gson().toJson(bean));
                    startActivity(intent);
                }
            }
        });

    }

    public static void start(Context context, String chatIM) {

        Intent intent = new Intent(context, MessageP2PActivity.class);
        intent.putExtra("chatIM", chatIM);
        context.startActivity(intent);

    }

    public static void start(Context context, String chatIM, String group_id) {

        Intent intent = new Intent(context, MessageP2PActivity.class);

        intent.putExtra("chatIM", chatIM);

        intent.putExtra("group_id", group_id);

        context.startActivity(intent);
    }

    public static void startHaveTitle(Context context, String chatIM, String cateStr,String demand) {

        Intent intent = new Intent(context, MessageP2PActivity.class);

        intent.putExtra("chatIM", chatIM);

        intent.putExtra("cateStr", cateStr);

        intent.putExtra("demand", demand);

        context.startActivity(intent);
    }

    public static void start(Context context, int userId, String orderJsonStr) {

        Intent intent = new Intent(context, MessageP2PActivity.class);

        intent.putExtra("chatIM", Integer.toString(userId));

        intent.putExtra("order", orderJsonStr);

        context.startActivity(intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        NimManager.getInstance().enterChat(chatIM);
        NimManager.getInstance().regOrUnregOnline(this, true);
        NimManager.getInstance().registerRcvListener(chatIM, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        WPHSdk.getService(MessageService.class).updateRecentMsgUnRead(group_id);
        NimManager.getInstance().regOrUnregOnline(this, false);
        NimManager.getInstance().quitChat();

        Intent intent=new Intent();
        intent.setAction("com.wpsd.audio.stop");
        sendBroadcast(intent);
    }

    @Override
    public void initData() {

//        if (getIntent().getBooleanExtra("BlueStatusbg",false)){
        if (Config.VERSION == 2 || Config.VERSION == 3) {
            StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorPrimaryBlue), false);
            /*if (Build.VERSION.SDK_INT >= 21) {
                View decorView = getWindow().getDecorView();
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
            }*/
            //ll_rootview.setPadding(0, DevicesUtil.getStatusBarHeight(this),0,0);
            tpl_title.setTitleBg(ContextCompat.getColor(this, R.color.colorPrimaryBlue));
            tpl_title.setCenterTitleTextColor(ContextCompat.getColor(this, R.color.white));
            tpl_title.setBackRes(ContextCompat.getDrawable(this, R.mipmap.common_icon_return_white));

            tpl_title.setAddViewRes(ContextCompat.getDrawable(this, R.mipmap.top_icon_chat_details));

        }
        if (getIntent() != null) {
            chatIM = getIntent().getStringExtra("chatIM");
            demand=getIntent().getStringExtra("demand");
            cateStr=getIntent().getStringExtra("cateStr");
            orderJsonStr = getIntent().getStringExtra("order");
        }
        if (TextUtil.isNotEmpty(chatIM)) {
            toUserInfo = NimManager.getInstance().getUser(chatIM, new RequestCallback() {
                @Override
                public void onSuccess(Object param) {
                    toUserInfo = NimManager.getInstance().getUser(chatIM, null);
                    initTitleText();
                }

                @Override
                public void onFailed(int code) {

                }

                @Override
                public void onException(Throwable exception) {

                }
            });
            initTitleText();
            //demand = "";
            group_id = getIntent().getStringExtra("group_id");
        }else{
            ToastManager.getInstance().showToast("请联系管理员，没有为该用户分配IM账号");
            finish();
            return;
        }
        if (TextUtil.isEmpty(group_id)) {
            if (chatIM.compareTo(userBean.getUser().getId()) > 0) {
                if (Integer.toString(getMsg_Type() / 10).compareTo(chatIM) > 0) {
                    group_id = userBean.getUser().getId() + ":" + chatIM + ":" + Integer.toString(getMsg_Type() / 10);
                } else if (Integer.toString(getMsg_Type() / 10).compareTo(userBean.getUser().getId()) < 0) {
                    group_id = Integer.toString(getMsg_Type() / 10) + ":" + userBean.getUser().getId() + ":" + chatIM;
                } else {
                    group_id = userBean.getUser().getId() + ":" + Integer.toString(getMsg_Type() / 10) + ":" + chatIM;
                }
            } else {
                if (Integer.toString(getMsg_Type() / 10).compareTo(chatIM) < 0) {
                    group_id = Integer.toString(getMsg_Type() / 10) + ":" + chatIM + ":" + userBean.getUser().getId();
                } else if (Integer.toString(getMsg_Type() / 10).compareTo(userBean.getUser().getId()) > 0) {
                    group_id = chatIM + ":" + userBean.getUser().getId() + ":" + Integer.toString(getMsg_Type() / 10);
                } else {
                    group_id = chatIM + ":" + Integer.toString(getMsg_Type() / 10) + ":" + userBean.getUser().getId();
                }
            }
        }
        if (TextUtil.isNotEmpty(demand)) {
            tv_info.setText(cateStr+" "+demand);
            tv_info.setVisibility(View.VISIBLE);
        } else {
            tv_info.setVisibility(View.GONE);
        }
        mAdapter.setUserBean(userBean);
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true);
        recv_msg_list.setLayoutManager(mLinearLayoutManager);
        recv_msg_list.setAdapter(mAdapter);
        checkConnectStatu();
        if (getMsg_Type() == WPHMsg.TYPE_SERVICE) {
            imv.hideTradeView(false);
        } else {
            imv.hideTradeView(false);
        }
        getData();
//      reflash();
    }

    private void initTitleText() {
        showTitle = "";
        if (toUserInfo != null && toUserInfo.getExtensionMap() != null && toUserInfo.getExtensionMap().get("type") != null) {
            int type = (int) toUserInfo.getExtensionMap().get("type");
            if (!TextUtil.equals(chatIM, "4") && type == 1) {
                showTitle = "客户" + " | ";
            }
            if (!TextUtil.equals(chatIM, "4") && type == 100) {
                showTitle = "工程商" + " | ";
            }

        }
        showTitle = (TextUtil.isNotEmpty(showTitle) ? showTitle : "") + (toUserInfo != null  && TextUtil.isNotEmpty(toUserInfo.getName())? toUserInfo.getName() : chatIM);
       /* if (NimManager.getInstance().isOnline()) {
            tpl_title.setTitle(showTitle);
        }*/
        tpl_title.setTitle(showTitle);
    }

    private void reflash() {

//        recv_msg_list.getSwipeToRefresh().post(new Runnable() {
//            @Override
//            public void run() {
//                recv_msg_list.setRefreshing(true);//执行下拉刷新的动画
//                refreshListener.onRefresh();//执行数据加载操作
//            }
//        });
    }


    private void getData() {
        progressBar.setVisibility(View.VISIBLE);
        loading = true;
        lastCrateAt = 0;
        if (mAdapter.getItemCount() > 0) {
            MsgBean bean = mAdapter.getData(mAdapter.getItemCount() - 1);
            if (bean != null) {
                lastCrateAt = bean.getCreated_at();
                if(lastCrateAt!=0 && lastCrateAt%1000==0)
                    lastCrateAt=lastCrateAt/1000;
            }
        }
        WPHSdk.getService(MessageService.class).getMsgList(chatIM, group_id, lastCrateAt, this);
    }


    @Override
    protected synchronized void unSub() {
        super.unSub();
    }

    private void checkConnectStatu() {
        boolean connected = NimManager.getInstance().isOnline();
        rl_tip_area.setVisibility(View.GONE);
        if (connected) {
//            sv.setVisibility(View.GONE);
            tpl_title.hideSpinView();
            tpl_title.setTitle(showTitle);
            if (TextUtil.isNotEmpty(orderJsonStr)) {
                NimManager.getInstance().sendOrderMsg(chatIM, getMsg_Type(), orderJsonStr, new NimManager.INNIMSendMsgListener() {
                    @Override
                    public void onSendMsg(MsgBean msgBean) {
                        mAdapter.addData(0, msgBean);
                        move(0);
                    }
                });
                orderJsonStr = null;
            }
        } else {
            tpl_title.hideSpinView();
//            sv.setVisibility(View.GONE);
            tpl_title.setTitle(chatIM + "(未连接)");
        }
    }

    @Override
    public void onConnecting() {
        rl_tip_area.setVisibility(View.GONE);
//        sv.setVisibility(View.VISIBLE);
        tpl_title.showSpinView();
        tpl_title.setTitle(showTitle + "(连接中...)");
    }

    @Override
    public void onConnected() {
        rl_tip_area.setVisibility(View.GONE);
//        sv.setVisibility(View.GONE);
        tpl_title.hideSpinView();
        tpl_title.setTitle(showTitle);
        if (TextUtil.isNotEmpty(orderJsonStr)) {
            NimManager.getInstance().sendOrderMsg(chatIM, getMsg_Type(), orderJsonStr, new NimManager.INNIMSendMsgListener() {
                @Override
                public void onSendMsg(MsgBean msgBean) {
                    mAdapter.addData(0, msgBean);
                    move(0);
                }
            });
            orderJsonStr = null;
        }
    }

    @Override
    public void onWaringTip(String msg, boolean reqLogin) {
        rl_tip_area.setVisibility(View.GONE);
//        sv.setVisibility(View.GONE);
        tpl_title.hideSpinView();
        tpl_title.setTitle(showTitle + "(未连接)");
        tv_msg_tip.setText(msg);
        if (reqLogin)
            btn_login.setVisibility(View.VISIBLE);
        else
            btn_login.setVisibility(View.GONE);
    }


    public boolean isSoftInputNotShow() {
        return Math.abs(mMaxHeight - ((ViewGroup) recv_msg_list.getParent()).getHeight()) < 10;
    }
//    public void setSoftInputShow(){
//        ViewGroup parentView = (ViewGroup)recv_msg_list.getParent();
//        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)parentView.getLayoutParams();
//        params.height = parentView.getHeight();
//        params.weight = 0;
//        parentView.requestLayout();
//    }
//
//    public void setSoftInputNotShow(){
//        ViewGroup parentView = (ViewGroup)recv_msg_list.getParent();
//        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)parentView.getLayoutParams();
//        params.height = 0;
//        params.weight = 1;
//        parentView.requestLayout();
//    }

//    @Override
//    public void onBackPressed() {
//        if (rl_softinput_bottom.getVisibility() == View.VISIBLE){
//            setSoftInputNotShow();
//            rl_softinput_bottom.setVisibility(View.GONE);
//        } else {
//            super.onBackPressed();
//        }
//    }

    @Override
    public void onMsgRcv(List<MsgBean> datas) {
        if (datas != null && datas.size() > 0) {
            for (MsgBean bean : datas) {
                mAdapter.addData(0, bean);
            }
        }
        move(0);
    }

    @Override
    public void onRecentMsgRcv(List<RecentMsgBean> datas) {

    }

    @Override
    public void onSuccess(Object var1) {
        progressBar.setVisibility(View.GONE);
        loading = false;
        mAdapter.addDatas((List) var1);
    }

    @Override
    public void onFailed(int var1, String message) {
        progressBar.setVisibility(View.GONE);
        loading = false;
        //recv_msg_list.setRefreshing(false);
    }

    @Override
    public void onException(Throwable var1) {
        progressBar.setVisibility(View.GONE);
        loading = false;
        //recv_msg_list.setRefreshing(false);
    }

    private int getMsg_Type() {
        int msg_type = MessageType.TYPE_NORMAL;
        if (TextUtil.equals(chatIM, "4"))
            msg_type = WPHMsg.TYPE_SERVICE;
        return msg_type;
    }

    @Override
    public void onSendTxtMsg(String msg) {
        if (TextUtil.isNotEmpty(msg)) {
            NimManager.getInstance().sendTxtMsg(chatIM, getMsg_Type(), WPHMsg.MSG_TXT, msg, new NimManager.INNIMSendMsgListener() {
                @Override
                public void onSendMsg(MsgBean msgBean) {
                  /*  List<MsgBean> mbs=new ArrayList<>();
                    mbs.add(msgBean);
                    PageMsgBean pmb=WPHSdk.getService(MessageService.class).setCatch(mbs);*/
                    mAdapter.addData(0, msgBean);
                    move(0);
                    //recv_msg_list.getRecyclerView().scrollToPosition(pmb.getDatas().size());
                }
            });

        }
    }


    @Override
    public boolean isHideBoa() {
        return false;
    }

    @Override
    public void onSelectPhoto() {
        PhotoPickManager.selectPicNoCamera(this, REQUEST_SELECT_PHOTO, 1, false, 0);
    }

    @Override
    public void onTakePhoto() {
        if (ContextCompat.checkSelfPermission(MessageP2PActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(
                    getString(R.string.mis_permission_rationale_write_storage));
        } else {
            mTmpFile = PhotoPickManager.showCameraAction(this, REQUEST_TAKE_PHOTO);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void requestPermission(String rationale) {
        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
//            new AlertDialog.Builder(MessageP2PActivity.this)
//                    .setTitle(me.nereo.multi_image_selector.R.string.mis_permission_dialog_title)
//                    .setMessage(rationale)
//                    .setPositiveButton(me.nereo.multi_image_selector.R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, MultiImageSelectorFragment.REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
//                        }
//                    })
//                    .setNegativeButton(me.nereo.multi_image_selector.R.string.mis_permission_dialog_cancel, null)
//                    .create().show();
        } else {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, MultiImageSelectorFragment.REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MultiImageSelectorFragment.REQUEST_STORAGE_WRITE_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mTmpFile = PhotoPickManager.showCameraAction(this, REQUEST_TAKE_PHOTO);
            }
        } else if(requestCode == REQUEST_RECORD_AUDIO){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // mTmpFile = PhotoPickManager.showCameraAction(this, REQUEST_TAKE_PHOTO);
            }
        }
        else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void onRequestPermission() {
        if(ContextCompat.checkSelfPermission(MessageP2PActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO);
        }
    }

    @Override
    public void onSelectDoc() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_SELECT_DOC);
    }

    @Override
    public void onSendAudio(String audioPath, int sends) {
        MessagesExt ext = new MessagesExt();
        ext.setFile_path(audioPath);
        ext.setFile_len(sends);
        NimManager.getInstance().sendAudioMsg(chatIM, getMsg_Type(), WPHMsg.MSG_VOICE, "", ext, new NimManager.INNIMSendMsgListener() {
            @Override
            public void onSendMsg(MsgBean msgBean) {
                /*List<MsgBean> mbs=new ArrayList<MsgBean>();
                mbs.add(msgBean);
                WPHSdk.getService(MessageService.class).setCatch(mbs);*/
                mAdapter.addData(0, msgBean);
                move(0);
                //recv_msg_list.getRecyclerView().scrollToPosition(pmb.getDatas().size());
            }
        });
    }

    @Override
    public void onTrade(boolean buy) {

        if (buy) {
            //买他产品
            if (userBean != null) {
                Intent intent = new Intent(MessageP2PActivity.this, ProductListActivity.class);
                intent.putExtra("buyer", Integer.parseInt(userBean.getUser().getId()));
                intent.putExtra("supplier", Integer.parseInt(chatIM));
                startActivity(intent);
            }
        } else {
            //卖他产品
            if (userBean != null) {
                Intent intent = new Intent(MessageP2PActivity.this, ProductListActivity.class);
                intent.putExtra("supplier", Integer.parseInt(userBean.getUser().getId()));
                intent.putExtra("buyer", Integer.parseInt(chatIM));
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_PHOTO) {
            if (data != null) {
                List<String> imgs = PhotoPickManager.getPhoto(data);
                setImgMessage(imgs);
            }
        } else if (requestCode == REQUEST_TAKE_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                Log.e("MessageP2PActivity","MessageP2PActivity======"+mTmpFile.exists()+","+mTmpFile.getAbsolutePath());
                if (mTmpFile != null) {
                    // notify system the image has change
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mTmpFile)));
                    String path = mTmpFile.getAbsolutePath();
                    List<String> imgs = new ArrayList<>();
                    imgs.add(path);
                    setImgMessage(imgs);
                }
            } else {
                // delete tmp file
                while (mTmpFile != null && mTmpFile.exists()) {
                    boolean success = mTmpFile.delete();
                    if (success) {
                        mTmpFile = null;
                    }
                }
            }
        } else if (requestCode == REQUEST_SELECT_DOC && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            sendFileMessage(uri);

        }
    }

    private void sendFileMessage(Uri uri) {
        String path = com.yunshl.yunshllibrary.utils.FileUtil.getRealPathFromUri(this, uri);
        if (path == null || path.length() <= 0) {
            showWarningText("文件不存在");
            return;
        }
        String name = path.substring(path.lastIndexOf("/") + 1, path.length());
        long size = FileUtil.getFileSize(new File(path));
        String type = FileUtil.getFileExtType(path);
        if (TextUtil.equals("doc", type) || TextUtil.equals("docx", type)
                || TextUtil.equals("ppt", type) || TextUtil.equals("pptx", type)
                || TextUtil.equals("xls", type) || TextUtil.equals("xlsx", type)
                || TextUtil.equals("pdf", type)) {

        } else {
            showWarningText("文件类型不支持");
            return;
        }
        MessagesExt ext = new MessagesExt();
        ext.setFile_path(path);
        ext.setFile_name(name);
        ext.setFile_len(size);
        ext.setFile_type(type);
        NimManager.getInstance().sendFileMsg(chatIM, getMsg_Type(), WPHMsg.MSG_DOC, "", ext, new NimManager.INNIMSendMsgListener() {
            @Override
            public void onSendMsg(MsgBean msgBean) {
               /* List<MsgBean> mbs=new ArrayList<MsgBean>();
                mbs.add(msgBean);
                WPHSdk.getService(MessageService.class).setCatch(mbs);*/
                mAdapter.addData(0, msgBean);
                move(0);
                //recv_msg_list.getRecyclerView().scrollToPosition(pmb.getDatas().size());
            }
        });
    }

    private void setImgMessage(List<String> paths) {
        if (paths != null && paths.size() > 0) {
            for (String path : paths) {
                MessagesExt ext = new MessagesExt();
                ext.setFile_path(path);
                NimManager.getInstance().sendImgMsg(chatIM, getMsg_Type(), WPHMsg.MSG_IMG, "", ext, new NimManager.INNIMSendMsgListener() {
                    @Override
                    public void onSendMsg(MsgBean msgBean) {
                       /* List<MsgBean> mbs=new ArrayList<MsgBean>();
                        mbs.add(msgBean);
                        WPHSdk.getService(MessageService.class).setCatch(mbs);*/
                        mAdapter.addData(0, msgBean);
                        move(0);
                        //recv_msg_list.getRecyclerView().scrollToPosition(pmb.getDatas().size());
                    }
                });
            }
        }
    }

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            recv_msg_list.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = recv_msg_list.getChildAt(n - firstItem).getTop();
            recv_msg_list.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            recv_msg_list.scrollToPosition(n);
            //这里这个变量是用在RecyclerView滚动监听里面的
            move = true;
        }

    }

    private void move(int n) {
        if (n < 0 || n >= mAdapter.getItemCount()) {
            // Toast.makeText(this,"超出范围了",Toast.LENGTH_SHORT).show();
            return;
        }
        mIndex = n;
        recv_msg_list.stopScroll();
        smoothMoveToPosition(0);
    }


    private void smoothMoveToPosition(int n) {

        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            recv_msg_list.smoothScrollToPosition(n);
        } else if (n <= lastItem) {
            int top = recv_msg_list.getChildAt(n - firstItem).getTop();
            recv_msg_list.smoothScrollBy(0, top);
        } else {
            recv_msg_list.smoothScrollToPosition(n);
            move = true;
        }

    }

    class RecyclerViewListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //在这里进行第二次滚动（最后的100米！）
            if (move) {
                move = false;
                //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < recv_msg_list.getChildCount()) {
                    //获取要置顶的项顶部离RecyclerView顶部的距离
                    int top = recv_msg_list.getChildAt(n).getTop();
                    //最后的移动
                    recv_msg_list.scrollBy(0, top);
                }
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (!isFinishing()) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(MessageP2PActivity.this).resumeRequests();
                } else {
                    Glide.with(MessageP2PActivity.this).pauseRequests();
                }
            }
        }
    }
}
